package com.admin.business.config.oss;

import com.alibaba.fastjson.JSONObject;
import com.admin.utils.ImgImageBase64Util;
import com.admin.utils.ResponseResult;
import org.apache.commons.io.FileUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@RestController
public class ImgUpload {
    //上传图片
    @RequestMapping("/uploadImg")
    public String uploadImg(@RequestBody String json,
                            HttpServletRequest request) throws IOException {
        try {
            JSONObject json_object = JSONObject.parseObject(json);
            MultipartFile file = OSSUtil.base64ToMultipart(json_object.get("base64").toString());
            String contentType = file.getContentType();
            String fileName = file.getOriginalFilename();
            String newFileName = fileName;
            System.out.println("fileName-->" + newFileName);
            System.out.println("getContentType-->" + contentType);
            //String filePath = request.getSession().getServletContext().getRealPath("imgupload/");
            String filePath = "C:\\test/";
            System.out.println(filePath);
            String key = OSSUtil.uploadPic(file, newFileName);
            System.out.println(key + "---------");
            if (key == null) {
                return null;
            }
            return key;
        } catch (Exception e) {
            //return ResponseResult.build(400, "上传失败!", "");
        }
        return null;
    }

    /**
     * 下载文件
     *
     * @param myFile
     * @param key
     * @return
     * @throws FileNotFoundException
     */
    @RequestMapping("/api/downlaod/config")
    public String downFile() {
        File file = FileUtils.getFile("config.json");
        if (!file.exists()) {
            OSSUtil.downFile();
        }
        System.err.println(file.getName());
        return "change?";
    }


    @RequestMapping(value = "/gouploadimg", method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView goUploadImg() {
        //跳转到 templates 目录下的 uploadimg.html
        ModelAndView mv = new ModelAndView();
        mv.setViewName("index");
        return mv;
    }

    //富文本上传图片
    @RequestMapping(value = {"/api/ue/uploadImg", "/ue/uploadImg", "/api/api/ue/uploadImg"})
    public Object uploadImage(HttpServletRequest request, HttpServletResponse response,
                              @RequestParam(value = "upfile", required = false) MultipartFile file,
                              @RequestParam("action") String action) {
        try {
            //获取jsonp回调
            String callback = (String) request.getParameter("callback");
            System.out.println("callback error:" + callback);
            //获取操作方式
            //String action = (String) request.getParameter("action");
            if (action.equals("config")) {
                //获取回调json
//                Map<String,String> callBackJson = new HashedMap();
                //ClassPathResource resource = new ClassPathResource("config.json");
                File files = FileUtils.getFile("config.json");
                if (!files.exists()) {
                    OSSUtil.downFile();
                    files = FileUtils.getFile("config.json");
                }
                //File files = resource.getFile();
                String jsonString = FileUtils.readFileToString(files, "UTF-8");

                JSONObject jsonObject = JSONObject.parseObject(jsonString);
                String callbackJson = jsonObject.toJSONString();

                //设置内容类型
                response.setContentType("application/javascript");
//                response.getWriter().write(callback+"("+callbackJson+")");
                return callback + "(" + callbackJson + ")";
                //return ResponseResult.build(200, "上传成功!", null);
            } else if (action.equals("uploadImage")) {
                Map<String, Object> map = new HashMap<>();
                //封装的图片上传方法
                //BASE64Encoder base64Encoder =new BASE64Encoder();
                //String base64EncoderImg = file.getOriginalFilename()+","+ base64Encoder.encode(file.getBytes());
                String url = ImgImageBase64Util.uploadImgFile(file, request);
                map.put("url", url.replace("http://clhy-img.oss-cn-beijing.aliyuncs.com", ""));//上传的图片路径
                map.put("state", "SUCCESS");
                map.put("type", "." + file.getOriginalFilename().split("\\.")[1]);
                map.put("title", file.getOriginalFilename());
                map.put("size", file.getSize());
                map.put("original", file.getOriginalFilename());
                return map;
                // return ResponseResult.build(200, "上传成功!", map);
            } else if (action.equals("uploadVideo")) {
                System.err.println("上传视频");

            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.build(400, "上传失败!", "");
        }
        return null;
    }

    //上传文件
    @RequestMapping("/ue/uploadFile")
    public Object uploadFile(HttpServletRequest request, HttpServletResponse response,
                             @RequestBody String json) {
        try {
            if (json.isEmpty()) {
                return ResponseResult.build(400, "数据无效!", "");
            }
            JSONObject jsonObject = JSONObject.parseObject(json);
            String file = jsonObject.getString("file");
            MultipartFile result = Base64Util.base64ToMultipart(file);
            String url = ImgImageBase64Util.uploadFile(result, request);
            return ResponseResult.build(200, "上传成功!", url);
        } catch (Exception e) {
            return ResponseResult.build(400, "上传失败!", "");
        }

    }

    /**
     * 获得cell内容
     *
     * @param cell
     * @return
     */
    public String getCellValue(XSSFCell cell) {
        String value = "";
        if (cell != null) {
            switch (cell.getCellType()) {
                case XSSFCell.CELL_TYPE_FORMULA:
                    break;
                case XSSFCell.CELL_TYPE_NUMERIC:
                    value = new BigDecimal(cell.getNumericCellValue() + "").intValue() + "";
                    break;
                case XSSFCell.CELL_TYPE_STRING:
                    value = cell.getStringCellValue().trim();
                    break;
                default:
                    value = "";
                    break;
            }
        }
        return value.trim();
    }

}